package com.bjpowernode.handler;

import cn.hutool.json.JSONUtil;
import com.bjpowernode.constant.Constant;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.result.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 应用退出成功处理器
 * 用于处理用户退出登录后的逻辑，包括清除Redis中的令牌和返回退出成功响应
 */
@Component
public class AppLogoutSuccessHandler implements LogoutSuccessHandler {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 处理退出成功逻辑
     * @param request HTTP请求对象
     * @param response HTTP响应对象
     * @param authentication 认证信息对象，包含当前登录用户信息
     * @throws IOException IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 设置响应内容类型为JSON，字符编码为UTF-8
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        // 从认证信息中获取当前登录用户对象
        TUser tUser = (TUser) authentication.getPrincipal();

        // 退出成功，删除Redis中存储的用户令牌
        redisTemplate.delete(Constant.REDIS_TOKEN_KEY + tUser.getId());
        // 采用构建器模式创建返回结果对象
        Result result = Result.builder().code(200).msg("退出成功").info(authentication).build();

        // 使用Hutool工具包将结果对象转换为JSON字符串
        String json = JSONUtil.toJsonStr(result);

        // 将JSON响应写入客户端
        response.getWriter().write(json);
    }
}
